
#include "NestPathItem.h"
#include <QGraphicsView>
#include <QListWidgetItem>
#include <QCheckBox>
#include <QMouseEvent>
#include <QMenu>
#include <QDebug>
#include <NestPathInfoDialog.h>

NestPathItem::NestPathItem(NestPath& nestPath, QWidget *parent) :
    QWidget(parent),
    m_nestPath(nestPath)
{
    this->setMinimumSize(200,200);
    auto* pathView = new QGraphicsView(this);
    auto* pathScence = new QGraphicsScene;
    auto* listItem = new QListWidgetItem;

    pathView->setScene(pathScence);
    listItem->setSizeHint(QSize(200,200));
    pathView->setFixedSize(200,200);
    // 将 QGraphicsPathItem 对象添加到 QGraphicsScene 中
    QGraphicsPathItem* item = NestPathToQGraphicsPathItem(m_nestPath);
    pathScence->addItem(item);
    checkbox = new QCheckBox(this);
    checkbox->move(180,0);
    checkbox->setChecked(true);

    m_path_name = new QLabel(this);
    m_path_name->setText(QString::fromStdString(m_nestPath.name));


}

QGraphicsPathItem* NestPathItem::NestPathToQGraphicsPathItem(NestPath& nestpath){
    QPolygonF polygonWithHole;
    for(int i=0;i<nestpath.size();i++){
        if (i == 0)
            polygonWithHole = nestpath[i]->toQPolygonF();
        else
            polygonWithHole = polygonWithHole.subtracted(nestpath[i]->toQPolygonF());
    }
    QPainterPath path;
    path.addPolygon(polygonWithHole);

    QGraphicsPathItem* item = new QGraphicsPathItem(path);
    item->setPen(QPen(Qt::black, 1));
    item->setBrush(QBrush(parts_color));

    return item;
}

void NestPathItem::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) // 如果是左键按下
    {
//        emit clicked(); // 发射自定义信号
        this->checkbox->toggle(); // 改变状态
    }else if(event->button() == Qt::RightButton){
        this->showContextMenu();
    }
    QWidget::mousePressEvent(event);
}

void NestPathItem::showContextMenu()
{
    QMenu* menu = new QMenu();
    QAction* action1 = new QAction("查看", this);
    QAction* action2 = new QAction("删除", this);
    menu->addAction(action1);
    menu->addAction(action2);

    connect(action1, &QAction::triggered, this, [=](){
        NestPathInfoDialog *binDialog = new NestPathInfoDialog(&this->m_nestPath, this);
        binDialog->setAttribute(Qt::WA_DeleteOnClose);
        binDialog->show();
    });
    connect(action2, &QAction::triggered, this, [=](){
        qDebug() << "Option 2 selected";
        emit deleteItem(m_nestPath.id);
    });

    menu->exec(QCursor::pos());
}

NestPathItem::~NestPathItem()
{
    qDebug()<<"NestPathItem析构";
}
